package com.fuyin.commons.component;

import com.alibaba.fastjson.JSONObject;
import com.fuyin.commons.response.BaseResponse;
import com.fuyin.commons.response.ErrorCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yuanxilan (yuanxilan@keep.com)
 * @Description 当未登录或者token失效访问接口时，自定义的返回结果
 * @date 2021年10月26日 2:53 下午
 * @since
 */

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONObject.toJSONString(BaseResponse.error(ErrorCode.UNAUTHORIZED, authException.getMessage())));
        response.getWriter().flush();
    }
}
